<template>
  <div>
    <div id="loadOverlay" class='loadingOverlay'>
      <ul id="loadbar" class="ins">
        <li>
          <div id="loadinglayer1" class="ball"></div>
          <div id="loadinglayer7" class="pulse"></div>
        </li>
        <li>
          <div id="loadinglayer2" class="ball"></div>
          <div id="loadinglayer8" class="pulse"></div>
        </li>
        <li>
          <div id="loadinglayer3" class="ball"></div>
          <div id="loadinglayer9" class="pulse"></div>
        </li>
        <li>
          <div id="loadinglayer4" class="ball"></div>
          <div id="loadinglayer10" class="pulse"></div>
        </li>
        <li>
          <div id="loadinglayer5" class="ball"></div>
          <div id="loadinglayer11" class="pulse"></div>
        </li>
      </ul>
    </div>
    <div id="mask" class="signmask"></div>


    <div id="centerDiv">
      <div id="redslibContainer" class="redslib-container" style="height:100%"></div>
    </div>

    <div class="test-btn">

      <button  @click="startDrawPoint()" v-if="panduan==true">开始标注(点)</button>
      <button  @click="startDrawPointxian()" v-if="panduan==true">开始标注(线)</button>
      <button  @click="startDrawPointmian()" v-if="panduan==true">开始标注(面)</button>
      <button  @click="baocunbiaohui()" v-if="panduan==false">保存标绘</button>
      <button  @click="deleteViewerEntity()">删除已标注</button>
      <!--            <button  @click="viewerEntityOnMap()">调用viewer上图</button>-->
      <!--            <button  @click="deleteViewerEntity()">删除viewer上图</button>-->
    </div>
    <!--   -->
    <div class="tan"  v-show="yonghuB">
      <div class="title_tan">
        <div style="width: 95%;float: left">用户信息</div>
        <div style="width: 5%;float: right;font-size: 16px"
             @click="handleClose">X</div>
      </div>
      <div >
        <el-select
          v-show="listpd==1"
          v-model="value"
          filterable
          placeholder="Select"
          style="width: 100%"
          @change="showYongHu"
        >
          <el-option
            v-for="item in yonghu"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
        <div v-if="listpd==2" style="padding: 10px;font-size: 12px;color:white"  v-for="item in yonghuList.list">
          用户姓名: {{item.realName}}
        </div>
        <div v-if="listpd==1">
          <el-button  type="primary" @click="baocun">保存</el-button>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
  import baseService from "@/service/baseService";
  import router from "../../router";

  export default {
    name: 'R3DMap',
    props: {
    },
    data() {
      return {
        panduan:true,
        craftbomId: this.$route.query.craftbomId,
        girdName: this.$route.query.girdName,
        gridOfVillageName: this.$route.query.gridOfVillageName,
        houseNum: this.$route.query.houseNum,
        title: 'R3D地图',
        drawControl: null,
        dialogVisible:true,
        yonghu:[
          {
            id:"1067246875800000064",
            label:"塍里"
          },
          {
            id:"1733419574956113921",
            label:"2-102"
          },
        ],
        yonghuList:[],
        value:"请选择用户",
        yonghuB:false,
        baocunyonghu:"",
        json1:{},
        listpd:0,
        biaozhulist:[],

      };

    },
    mounted() {
      this.initMap();

    },
    methods: {
      baocunbiaohui(){
        var arr = this.drawControl.toGeoJSON();
        baseService.post("/clc/clcmapnodeinfo",
          {jsonInfo: JSON.stringify(arr.features[0]),pointId:this.craftbomId,deptId:this.craftbomId})
          .then((results) => {
            //debugger
            debugger
            var strjson = results;
            var isClearForOpenFile = false; //是否清除已上图的entity
            var isFly = true; //上图后是否飞行到entity
            //
            // this.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
            baseService.put("/clcLocationMark/clclocationmark",
              {id:this.craftbomId,locationMarkId:this.craftbomId})
              .then((results) => {
                this.$router.back(0)
              });

          });
        this.panduan=false
        console.log(arr)
      },
      startDrawPointxian() {
        debugger
        this.panduan=false
        let pointDefval = {
          "edittype": "polyline",
          "name": "点标记",
          "style": {
            "pixelSize": 10,
            "color": "#3388ff",
            "opacity": 1,
            "outline": true,
            "outlineColor": "#ffffff",
            "outlineOpacity": 0.6,
            "outlineWidth": 2,
            "disableDepthTestDistance":100000,
            "scaleByDistance":true,
            "scaleByDistance_far":10000,
            "clampToGround":true

          },
          "attr": {
            "id": this.craftbomId,
            "name": this.girdName+"-"+this.gridOfVillageName+"-"+this.houseNum
          },
          "type": "polyline"
        }
        this.drawControl.startDraw(pointDefval);
      },
      startDrawPointmian() {
        debugger
        // "color": "#3388ff",
        this.panduan=false
        let pointDefval = {
          "edittype": "polygon",
          "name": "点标记",
          "style": {
            "pixelSize": 10,
            "color": "#3388ff",
            "opacity": 0.1,
            "outline": true,
            "outlineColor": "#ffffff",
            "outlineOpacity": 0.6,
            "outlineWidth": 2,
            "disableDepthTestDistance":100000,
            "scaleByDistance":true,
            "scaleByDistance_far":10000,
            "clampToGround":true

          },
          "attr": {
            "id": this.craftbomId,
            "name": this.girdName+"-"+this.gridOfVillageName+"-"+this.houseNum
          },
          "type": "polygon"
        }
        this.drawControl.startDraw(pointDefval);
      },
      startDrawPoint() {
        debugger
        this.panduan=false
        let pointDefval = {
          "edittype": "point",
          "name": "点标记",
          "style": {
            "pixelSize": 10,
            "color": "#3388ff",
            "opacity": 1,
            "outline": true,
            "outlineColor": "#ffffff",
            "outlineOpacity": 0.6,
            "outlineWidth": 2,
            "disableDepthTestDistance":100000,
            "scaleByDistance":true,
            "scaleByDistance_far":10000
          },
          "attr": {
            "id": this.craftbomId,
            "name": this.girdName+"-"+this.gridOfVillageName+"-"+this.houseNum
          },
          "type": "point"
        }
        this.drawControl.startDraw(pointDefval);
      },
      baocun(){
        let that = this

        let pointId =that.json1.features[that.json1.features.length-1].properties.attr.id
        if( document.getElementsByClassName('redslib-viewer')[0]){
          baseService.post("/clc/clcmapnodeinfo",
            {jsonInfo: JSON.stringify(that.json1.features[that.json1.features.length-1]),pointId:pointId,deptId:that.baocunyonghu})
            .then((results) => {
              //debugger
              var strjson = results;
              var isClearForOpenFile = false; //是否清除已上图的entity
              var isFly = true; //上图后是否飞行到entity

              that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
            });
        }else {
          baseService.post("/clc/clcmapnodeinfo",
            {jsonInfo: JSON.stringify(that.json1.features[that.json1.features.length-1]),pointId:pointId,deptId:that.baocunyonghu})
            .then((results) => {
              //debugger

              var strjson = results;
              var isClearForOpenFile = false; //是否清除已上图的entity
              var isFly = true; //上图后是否飞行到entity

              that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
            });
        }
        this.yonghuB=false
      },
      //校验权限
      handleClose() {
        this.yonghuB=false
      },
      initDrawControl(viewer) {
        this.drawControl = new reds3d.Draw({
          viewer: viewer,
          // hasEdit: true,
          tooltip: true
        });
      },
      initMap() {
        let that = this;
        var request = haoutil.system.getRequest();
        var configfile = "/chenglicun/r3dUtil/config/config.json";
        // var configfile = "http://localhost:8019/data/mapConfig.json";
        if (request.config)
          configfile = request.config;
        haoutil.loading.show();
        if( document.getElementsByClassName('redslib-viewer')[0]){
          document.getElementsByClassName('redslib-viewer')[0].remove()
          reds3d.createMap({
            id: 'redslibContainer',
            // url: configfile + "?time=20231104",
            url: configfile,
            success: function (_viewer, gisdata, jsondata) {//地图成功加载完成后执行


              haoutil.loading.hide();
              window.viewer = _viewer;
              //初始化widget管理器
              var hasAnimation = true;
              if (haoutil.isutil.isNotNull(request.widget)) {
                jsondata.widget.widgetsAtStart = [];
                hasAnimation = false;
              }
              reds3d.widget.init(_viewer, jsondata.widget);
              that.initDrawControl(_viewer);
              debugger
              console.log(that.craftbomId)
              baseService.get("clc/clcmapnodeinfo/getInfoByPointId/?pointId="+that.craftbomId)
                .then((results) => {
                  debugger
                  let biaozhu = [results.data.jsonInfo]
                  let a = {
                    features:biaozhu,
                    type: "FeatureCollection"
                  }
                  var strjson= a
                  var isClearForOpenFile = true; //是否清除已上图的entity
                  var isFly = true; //上图后是否飞行到entity
                  // that.biaozhulist[0]=results.data.jsonInfo
                  that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
                });

              // $.ajax({
              //   type: "get",
              //   url:  "https://project.jiusegongyi.com/chenglicun-admin/clc/clcmapnodeinfo/getInfo",
              //   async: false,
              //   success: function (results) {
              //     var strjson = results.data;
              //     var isClearForOpenFile = true; //是否清除已上图的entity
              //     var isFly = true; //上图后是否飞行到entity
              //
              //     that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
              //   }
              // });
              // 接受消息
              window.addEventListener('message', e => {
                if (e.data.type !== 'draw') return;
                if(e.data.widgets == 'plot-api'){ //接收标绘组件发送的消息
                  //debugger
                  console.log('标绘json:', e.data.data);
                  that.json1= e.data.data
                  that.yonghuB=true
                  that.listpd=1

                  // $.ajax({
                  //   type: "post",
                  //   url:  "https://project.jiusegongyi.com/chenglicun-admin/clc/clcmapnodeinfo",
                  //   async: false,
                  //   contentType: "application/json",
                  //   data:JSON.stringify({jsonInfo: JSON.stringify(e.data.data.features[e.data.data.features.length-1])}),
                  //   success: function (results) {
                  //     //debugger
                  //     var strjson = results;
                  //     var isClearForOpenFile = false; //是否清除已上图的entity
                  //     var isFly = true; //上图后是否飞行到entity
                  //
                  //     that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
                  //
                  //   }
                  // });
                  const data = e.data.data;
                  if (!data) return;

                  //测试：保存到本地
                  //   saveJSON(data, 'data.json')
                }
              })
              setTimeout(function () {
                $("#mask").remove();
              }, 3000);
              that.loaderOK();

              window.viewer.screenSpaceEventHandler.setInputAction(async (move) => {
                const pickedObj = window.viewer.scene.pick(move.position)
                console.log(pickedObj)
              }, Redslib.ScreenSpaceEventType.RIGHT_CLICK)

              //如果有xyz传参，进行定位
              if (haoutil.isutil.isNotNull(request.x) && haoutil.isutil.isNotNull(request.y)) {
                window.viewer.wing.centerAt(request, { duration: 0, isWgs84: true });
              }

              function calback() {
                //如果url传参，激活对应widget
                if (haoutil.isutil.isNotNull(request.widget))
                  reds3d.widget.activate(request.widget);
                that.initWork(_viewer);
              }

              // if (hasAnimation) //开场动画
              //   window.viewer.wing.openFlyAnimation(calback); //动画播放完成后执行calback回调
              // else {
              //   calback();
              // }
            }
          });
        }else {
          reds3d.createMap({
            id: 'redslibContainer',
            // url: configfile + "?time=20231104",
            url: configfile,
            success: function (_viewer, gisdata, jsondata) {//地图成功加载完成后执行


              haoutil.loading.hide();
              window.viewer = _viewer;
              //初始化widget管理器
              var hasAnimation = true;
              if (haoutil.isutil.isNotNull(request.widget)) {
                jsondata.widget.widgetsAtStart = [];
                hasAnimation = false;
              }
              reds3d.widget.init(_viewer, jsondata.widget);
              that.initDrawControl(_viewer);

              //
              // baseService.get("/clc/clcmapnodeinfo/getInfo")
              //   .then((results) => {
              //
              //     var strjson = results.data;
              //     var isClearForOpenFile = true; //是否清除已上图的entity
              //     var isFly = true; //上图后是否飞行到entity
              //     that.biaozhulist=results.data
              //     that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
              //   });

              // $.ajax({
              //   type: "get",
              //   url:  "https://project.jiusegongyi.com/chenglicun-admin/clc/clcmapnodeinfo/getInfo",
              //   async: false,
              //   success: function (results) {
              //     var strjson = results.data;
              //     var isClearForOpenFile = true; //是否清除已上图的entity
              //     var isFly = true; //上图后是否飞行到entity
              //
              //     that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
              //   }
              // });
              // 接受消息
              window.addEventListener('message', e => {

                if (e.data.type !== 'draw') return;
                if(e.data.widgets == 'plot-api'){ //接收标绘组件发送的消息
                  //debugger
                  console.log('标绘json:', e.data.data);
                  that.json1= e.data.data
                  that.yonghuB=true
                  that.listpd=1

                  // $.ajax({
                  //   type: "post",
                  //   url:  "https://project.jiusegongyi.com/chenglicun-admin/clc/clcmapnodeinfo",
                  //   async: false,
                  //   contentType: "application/json",
                  //   data:JSON.stringify({jsonInfo: JSON.stringify(e.data.data.features[e.data.data.features.length-1])}),
                  //   success: function (results) {
                  //     //debugger
                  //     var strjson = results;
                  //     var isClearForOpenFile = false; //是否清除已上图的entity
                  //     var isFly = true; //上图后是否飞行到entity
                  //
                  //     that.drawControl.jsonToEntity(strjson, isClearForOpenFile, isFly);
                  //
                  //   }
                  // });
                  const data = e.data.data;
                  if (!data) return;

                  //测试：保存到本地
                  //   saveJSON(data, 'data.json')
                }
              })
              setTimeout(function () {
                $("#mask").remove();
              }, 3000);
              that.loaderOK();

              // 进入
              window.viewer.screenSpaceEventHandler.setInputAction(async (move) => {
                const pickedObj = window.viewer.scene.pick(move.position)
                console.log(pickedObj)
                const a =   pickedObj.id._attribute.attr.id
                var entityArr = this.drawControl.getEntitys();
                for (let i = 0; i < entityArr.length; i++) {
                  console.log('entityArr:', entityArr[i]);
                  entityArr[i].popup = {
                    html: `<div style="width: 224px; height: 50px;"><p style="color: #ff0000;">测试弹窗内容</p></div>`,
                    anchor: [0, -60]
                  };
                  // entityArr[i].tooltip = {
                  //               html: `<div style='min-width: 200px;text-align: center'>tooltip111</div>`
                  //           };

                }
                that.chaYongHu(a)
                that.yonghuB=true
                that.listpd=2
              }, Redslib.ScreenSpaceEventType.LEFT_CLICK)

              //如果有xyz传参，进行定位
              if (haoutil.isutil.isNotNull(request.x) && haoutil.isutil.isNotNull(request.y)) {
                window.viewer.wing.centerAt(request, { duration: 0, isWgs84: true });
              }

              function calback() {
                //如果url传参，激活对应widget
                if (haoutil.isutil.isNotNull(request.widget)) {
                  reds3d.widget.activate(request.widget);
                }
                that.initWork(_viewer);
              }

              if (hasAnimation) //开场动画
                window.viewer.wing.openFlyAnimation(calback); //动画播放完成后执行calback回调
              else {
                calback();
              }
            }
          });
        }




      },
      loaderOK() {
        $("#loadOverlay").hide();
        $('#loadbar').removeClass('ins');
        Window.LOADING_FLAG = true;
      },
      initWork(viewer) {
        haoutil.oneMsg('如果未出现地球，是因为地形加载失败，请刷新重新加载！', 'terrain_tip');
        // 禁用默认的实体双击动作。
        viewer.screenSpaceEventHandler.removeInputAction(Redslib.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
        viewer.screenSpaceEventHandler.removeInputAction(Redslib.ScreenSpaceEventType.LEFT_CLICK);

        //移动设备上禁掉以下几个选项，可以相对更加流畅
        if (!haoutil.system.isPCBroswer) {
          viewer.targetFrameRate = 20; //限制帧率
          viewer.requestRenderMode = true; //取消实时渲染
          viewer.scene.fog.enable = false;
          viewer.scene.skyAtmosphere.show = false;
          viewer.scene.fxaa = false;
        }

        //IE浏览器优化
        if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
          viewer.targetFrameRate = 20; //限制帧率
          viewer.requestRenderMode = true; //取消实时渲染
        }

        //更改配置，性能优化
        viewer.scene.logarithmicDepthBuffer = false;


        //设置操作习惯,更换中键和右键
        viewer.scene.screenSpaceCameraController.tiltEventTypes = [
          Redslib.CameraEventType.RIGHT_DRAG, Redslib.CameraEventType.PINCH,
          { eventType: Redslib.CameraEventType.LEFT_DRAG, modifier: Redslib.KeyboardEventModifier.CTRL },
          { eventType: Redslib.CameraEventType.RIGHT_DRAG, modifier: Redslib.KeyboardEventModifier.CTRL }
        ];
        // MOUSE_MOVE
        viewer.scene.screenSpaceCameraController.zoomEventTypes = [Redslib.CameraEventType.MIDDLE_DRAG, Redslib.CameraEventType.WHEEL, Redslib.CameraEventType.PINCH];
      },

      showWidgets() {
        reds3d.widget.activate({
          uri: "/chenglicun/r3dUtil/map/widgets/toolBarRight/widget.js", //右上角工具栏组件
          data: [
            {
              "name": "图层",
              "icon": "fa fa-tasks",
              "widget": "/chenglicun/r3dUtil/map/widgets/manageLayers/widget.js",
              "visible": true
            },
            {
              "name": "标绘",
              "icon": "fa fa-object-group",
              "widget": "/chenglicun/r3dUtil/map/widgets/plot-api/widget.js",
              "visible": true
            }
          ]
        });
      },
      showYongHu(value){
        const deptId = {
          deptId:value
        }

        this.baocunyonghu=value
        baseService.get("/sys/user/page",deptId)
          .then((results) => {

            this.yonghuList =results.data

          });
      },
      chaYongHu(value){
        let  deptId = {
          deptId:""
        }
        let pointId ={
          pointId:value
        }

        baseService.get("/clc/clcmapnodeinfo/getInfoByPointId",pointId)
          .then((results) => {

            deptId = {
              deptId:results.data.deptId
            }
            baseService.get("/sys/user/page",deptId)
              .then((results) => {
                this.yonghuList =results.data

              });
          });

        // console.log(this.biaozhulist)
        // for(var i =0; i<this.biaozhulist.features.length;i++){
        //   debugger
        //   if(this.biaozhulist.features[i].properties==value){
        //     debugger
        //     let pointId ={
        //       pointId:this.biaozhulist[i].pointId
        //     }
        //
        // }


      },
      drawEntityByJson() {
        // 获取本地json
        $.ajax({
          type: "get",
          url:  "/chenglicun/r3dUtil/map/test1.json",
          async: false,
          success: function (results) {
            var strjson = results; //上图json
            var isClearForOpenFile = true; //是否清除已上图的entity
            var isFly = true; //上图后是否飞行到entity

            var plotWidget = reds3d.widget.getClass('/chenglicun/r3dUtil/map/widgets/plot-api/widget.js');
            if (plotWidget) {
              plotWidget.jsonToLayer(strjson, isClearForOpenFile, isFly)
            }else{
              haoutil.alert('标绘组件未打开');
            }
          }
        });
      },
      deletePlotEntity() {
        var plotWidget = reds3d.widget.getClass('/chenglicun/r3dUtil/map/widgets/plot-api/widget.js');
        if (plotWidget) {
          plotWidget.deleteAll();
        }
      },
      viewerEntityOnMap(){
        //添加图标点
        window.viewer.entities.add({
          id: "point_1",
          name: "测试点",
          position: Redslib.Cartesian3.fromDegrees(120.466753, 31.655606, 6),
          billboard: {
            image: '/chenglicun/r3dUtil/map/img/marker/mark1.png',
            horizontalOrigin: Redslib.HorizontalOrigin.CENTER,
            verticalOrigin: Redslib.VerticalOrigin.BOTTOM,
            scale: 0.5,
          },
          tooltip: { html: `<div style='min-width: 200px;text-align: center'>测试名称</div>` },
          popup: {
            html: `
                <div style = "width: 200px; height: 50px;">
                    <p>弹窗测试内容一</p>
                    <p>弹窗测试内容一二</p>
                </div>
                `,
            anchor: [0, -20]
          }
        });
      },
      deleteViewerEntity() {
        this.panduan=true
          this.drawControl.deleteAll();

      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  h3 {
    margin: 40px 0 0;
  }
  ul {
    list-style-type: none;
    padding: 0;
  }
  li {
    display: inline-block;
    margin: 0 10px;
  }
  a {
    color: #121414;
  }
  .test-btn{

    top: 0;
    left: 0;
    display: inline-grid;
  }
  .tips{
    position: absolute !important;
    top: 10%;

  }
  .tan{
    padding: 10px;
    position: absolute;
    top: 10%;
    left: 10%;
    width: 300px;
    height: 300px;
    color: #FFFFFF;
    background-color: rgba(30,36,50,0.6);
    border: 0;
  }
  .title_tan{
    width: 100%;
    height: 40px;
    font-size: 24px;
    line-height: 40px;
  }
</style>
